package db

import (
	"fmt"
	"pan/db/mysql"
)

// UserSignUp: 用户注册
func UserSignUp(username, passwd string) bool {
	sql := "INSERT IGNORE INTO user (user_name, user_pwd) VALUES(?, ?)"
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare insert sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Exec(username, passwd)
	if err != nil {
		fmt.Printf("excute insert sql fail err:%s\n", err.Error())
		return false
	}
	rows, err := ret.RowsAffected()
	if err == nil && rows > 0 {
		return true
	}
	return false
}

// UserSignIn: 用户登录
func UserSignIn(username, encryptPwd string) bool {
	sql := "SELECT user_pwd FROM user WHERE user_name = ? LIMIT 1"
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare user select sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Query(username)
	if err != nil {
		fmt.Printf("user query sql fail err:%s\n", err.Error())
		return false
	}
	if ret == nil {
		fmt.Println("username not found")
		return false
	}
	pRows := mysql.ParseRows(ret)
	if len(pRows) > 0 && string(pRows[0]["user_pwd"].([]byte)) == encryptPwd {
		return true
	}
	return false
}

// UpdateToken: 刷新用户token
func UpdateToken(username, token string) bool {
	sql := "REPLACE INTO user_token (user_name, user_token) VALUES(?, ?)"
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare replace sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	_, err = stmt.Exec(username, token)
	if err != nil {
		fmt.Printf("excute replace sql fail err:%s\n", err.Error())
		return false
	}
	return true
}

// ValidUserToken: 验证token
func ValidUserToken(username, token string) bool {
	// 验证token长度
	if len(token) != 40 {
		return false
	}
	// 验证token过期了没
	// 能否查到token
	sql := "SELECT id FROM user_token WHERE user_name = ? AND user_token = ? LIMIT 1"
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare token select sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Query(username, token)
	if err != nil {
		fmt.Printf("user query sql fail err:%s\n", err.Error())
		return false
	}
	if ret == nil {
		fmt.Println("token not found")
		return false
	}
	pRows := mysql.ParseRows(ret)
	return len(pRows) > 0
}

// User: user信息结构体
type User struct {
	Username string
	SignUpAt string
}

// GetUserInfo: 获取用户信息
func GetUserInfo(username string) (User, error) {
	user := User{}
	sql := "SELECT user_name, signup_at FROM user WHERE user_name = ? LIMIT 1"
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		return user, err
	}
	defer stmt.Close()
	err = stmt.QueryRow(username).Scan(&user.Username, &user.SignUpAt)
	if err != nil {
		return user, err
	}
	return user, nil
}
